<?php

namespace app\api\controller;

use app\api\ApiBaseController;
use app\common\service\Request;
use app\common\service\Wechat;
use app\merchant\model\ExpenseRecordModel;
use app\merchant\model\MerchantModel;
use app\merchant\model\VerificationModel;
use app\pilot\model\BalanceRecordModel;
use app\pilot\model\PilotModel;
use app\task\model\CategoryModel;
use app\task\model\OrderModel;
use app\task\model\TaskModel;
use think\Exception;
use think\facade\Db;

/**
 * 商户
 */
class Merchant extends ApiBaseController
{
    /**
     * 不需要验证登录的接口
     * @var bool
     */
    public $noNeedLoginAuth = ['login'];

    /**
     * 登录
     */
    public function login()
    {
        try{
            $input = $this->request->post();
            // 微信code
            $code = $input['code'] ?? '';
            // 推荐人id
            $referer_id    = $input['referer_id'] ?? 0;
            if (empty($code)) $this->error('缺少code');
            // 请求微信接口获取openid和unionid
            $res = Wechat::WeMiniCrypt('merchant')->session($code);
            $openid = $res['openid'] ?? '';
            if (empty($openid)) $this->error('缺少openid');
            $unionid = $res['unionid'] ?? '';
            $token = rand_str();
            $timeout = strtotime("+15 days");
            Db::startTrans();
            $merchant = MerchantModel::where('openid', $openid)->findOrEmpty();
            if ($merchant->isEmpty()) {
                $referer = MerchantModel::where('referer_id', $referer_id)->find();
                if (!empty($referer)) $merchant->referer_id = $referer_id;
                $merchant->openid = $openid;
                $merchant->unionid = $unionid;
                $merchant->nickname = '微信用户';
                $merchant->token = $token;
                $merchant->timeout = $timeout;
            }else{
                if (time() > $merchant->timeout - 200){
                    $merchant->token = $token;
                    $merchant->timeout = $timeout;
                }
            }
            $merchant->login_at = date('Y-m-d H:i:s');
            $merchant->login_num += 1;
            $merchant->login_ip = $this->app->request->ip();
            $merchant->save();
            Db::commit();
            $result = [
                'token'     => $merchant->token,
                'timeout'  => $merchant->timeout,
            ];
            $this->success('ok', $result);
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 微信获取手机号
     */
    public function wxGetPhone()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $input = $this->request->post();
        // 微信code，换取手机号
        $code = $input['code'] ?? '';

        $merchant = MerchantModel::where('id', $merchant['id'])->find();
        try {
            $res = Wechat::WeMiniCrypt('merchant')->getPhoneNumber($code);
            $merchant->phone = $res['phone_info']['phoneNumber'];
            $merchant->save();
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('ok', [
            'phone' => $merchant->phone,
        ]);
    }

    /**
     * 获取分享二维码
     */
    public function qrcode()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $baseurl = dirname(request()->baseFile(true));
        $separator = DIRECTORY_SEPARATOR;
        $filepath = "upload{$separator}qrcode{$separator}merchant{$separator}{$merchant['openid']}.png";
        $url = $baseurl.$separator.$filepath;
        if (file_exists($filepath)){
            $this->success('ok', $url);
        }else{
            // 获取二维码
            try {
                $referer_id = $merchant['id'] ?? 0;
                $res = Wechat::WeMiniQrcode('merchant')->createMiniScene($referer_id, '', 300, false, null, true);
                if (!is_dir(dirname($filepath))) mkdir(dirname($filepath), 0777, true);
                if (file_put_contents($filepath, $res)) {
                    $this->success('ok', $url);
                } else {
                    $this->error('二维码保存失败');
                }
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
        }

    }

    /**
     * 商户信息
     */
    public function userInfo()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $user_info = array_keep(request()->merchant, [
            'nickname','avatar','phone','qq','email','expense','realname','company','id_company', 'is_verification', 'id_card'
        ]) ;
        $this->success('ok', $user_info);
    }

    /**
    * 更新商户信息
    */
    public function saveInfo()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');
        if (empty($merchant['phone'])) $this->error('请先登录');

        $merchant = MerchantModel::where('id', $merchant['id'])->find();
        $input = $this->request->post();
        // 更新昵称头像
        if (!empty($input['nickname'])) $merchant->nickname = $input['nickname'];
        if (!empty($input['avatar'])) $merchant->avatar = $input['avatar'];
        // 更新个人认证信息
        if (!empty($input['realname'])) $merchant->realname = $input['realname'];
        if (!empty($input['id_card'])) {
            $merchant->id_card = $input['id_card'];
            // 定义身份证号码的正则表达式
            $regex = '/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/';
            if (!preg_match($regex, $merchant->id_card)) $this->error('身份证号码格式错误');
        }
        // 更新企业认证信息
        if (!empty($input['company'])) $merchant->company = $input['company'];
        if (!empty($input['id_company'])) $merchant->id_company = $input['id_company'];
        $merchant->save();
        $this->success('ok');
    }

    /**
     * 配置数据
     */
    public function config()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $config['service_wechat_qrcode']  = sysconf('service_wechat_qrcode');
        $config['service_phone']  = sysconf('service_phone');
        $config['service_time']  = sysconf('service_time');

        $this->success('ok', $config);
    }

    /**
     * 配置数据
     */
    public function note()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $config['merchant_note']  = htmlspecialchars_decode(sysconf('merchant_note'));

        $this->success('ok', $config);
    }

    /**
     * 配置数据
     */
    public function agreement()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $config['merchant_agreement']  = htmlspecialchars_decode(sysconf('merchant_agreement'));

        $this->success('ok', $config);
    }

    /**
     * 账单记录列表
     */
    public function expenseRecordList()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $query = ExpenseRecordModel::with(['task_order'])
            ->where('merchant_id', $merchant['id']);
        $list = get_list($query);
        // 数据清洗
//        foreach ($list['list'] as &$vo){
//            $vo['task_order'] = array_keep($vo['category'], ['id', 'name', 'img']);
//        }
        $this->success('ok', $list);
    }

    /**
     * 一键发布任务
     */
    public function addTaskOneKey()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');
        if (empty($merchant['phone'])) $this->error('请先登录');

        $input = $this->request->post();
        $data = [
            'category_id' => $input['category_id'] ?? 0,
            'exec_at' => $input['exec_at'] ?? '',
            'name' => $input['name'] ?? '',
            'desc' => $input['desc'] ?? '',
            'require' => $input['require'] ?? '',
            'money' => floatval($input['money'] ?? 0),
            'province' => $input['province'] ?? '',
            'city' => $input['city'] ?? '',
            'area' => $input['area'] ?? '',
            'address' => $input['address'] ?? '',
            'file' => $input['file'] ?? '',
            'file_name' => $input['file_name'] ?? '',
            'lat' => $input['lat'] ?? 0,
            'lng' => $input['lng'] ?? 0,
        ];

        // 发单的商户
        $data['merchant_id'] = $merchant['id'];

        if (empty($data['category_id'])) $this->error('订单任务类型不能为空');
        $category = CategoryModel::where(['is_deleted'=>0, 'status'=>1])->where('id', $data['category_id'])->find();
        if (empty($category)) $this->error('订单任务类型不存在');

        if (empty($data['exec_at'])) $this->error('订单任务时间不能为空');
        if(strtotime($data['exec_at']) === false) $this->error('订单任务时间格式不正确');

        if (empty($data['name'])) $this->error('订单任务名称不能为空');

        if (empty($data['province']) || empty($data['city']) || empty($data['area'])) $this->error('订单任务地区不正确');

        if (empty($data['address'])) $this->error('订单任务详细地址不能为空');

//        if (empty($data['desc'])) $this->error('订单任务描述不能为空');

//        if (empty($data['require'])) $this->error('订单任务要求不能为空');

        if (empty($data['money'])) $this->error('订单任务报酬不能为空');

//        if (empty($data['file'])) $this->error('审批文件不能为空');

        $data['place'] = $data['province'].$data['city'].$data['area'].$data['address'];

        $data['latlng'] = $data['lat'].','.$data['lng'];

        $data['task_status'] = TaskModel::TASK_STATUS__PENDING_REVIEW;

        TaskModel::create($data);

        $this->success('ok');
    }

    /**
     * 发布任务
     */
    public function addTask()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');
        if (empty($merchant['phone'])) $this->error('请先登录');

        $input = $this->request->post();
        $data = [
            'category_id' => $input['category_id'] ?? 0,
            'exec_at' => $input['exec_at'] ?? '',
            'name' => $input['name'] ?? '',
            'desc' => $input['desc'] ?? '',
            'require' => $input['require'] ?? '',
            'money' => floatval($input['money'] ?? 0),
            'province' => $input['province'] ?? '',
            'city' => $input['city'] ?? '',
            'area' => $input['area'] ?? '',
            'address' => $input['address'] ?? '',
            'file' => $input['file'] ?? '',
            'file_name' => $input['file_name'] ?? '',
            'lat' => $input['lat'] ?? 0,
            'lng' => $input['lng'] ?? 0,
        ];

        // 发单的商户
        $data['merchant_id'] = $merchant['id'];

        if (empty($data['category_id'])) $this->error('订单任务类型不能为空');
        $category = CategoryModel::where(['is_deleted'=>0, 'status'=>1])->where('id', $data['category_id'])->find();
        if (empty($category)) $this->error('订单任务类型不存在');

        if (empty($data['exec_at'])) $this->error('订单任务时间不能为空');
        if(strtotime($data['exec_at']) === false) $this->error('订单任务时间格式不正确');

        if (empty($data['name'])) $this->error('订单任务名称不能为空');

        if (empty($data['province']) || empty($data['city']) || empty($data['area'])) $this->error('订单任务地区不正确');

        if (empty($data['address'])) $this->error('订单任务详细地址不能为空');

        if (empty($data['desc'])) $this->error('订单任务描述不能为空');

        if (empty($data['require'])) $this->error('订单任务要求不能为空');

        if (empty($data['money'])) $this->error('订单任务报酬不能为空');

        if (empty($data['file'])) $this->error('审批文件不能为空');

        $data['place'] = $data['province'].$data['city'].$data['area'].$data['address'];

        $data['latlng'] = $data['lat'].','.$data['lng'];

        $data['task_status'] = TaskModel::TASK_STATUS__PENDING_REVIEW;

        TaskModel::create($data);

        $this->success('ok');
    }

    /**
     * 编辑任务
     */
    public function editTask()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');
        if (empty($merchant['phone'])) $this->error('请先登录');

        $input = $this->request->post();
        $data = [
            'id' => $input['id'] ?? 0,
            'category_id' => $input['category_id'] ?? 0,
            'exec_at' => $input['exec_at'] ?? '',
            'name' => $input['name'] ?? '',
            'desc' => $input['desc'] ?? '',
            'require' => $input['require'] ?? '',
            'money' => floatval($input['money'] ?? 0),
            'province' => $input['province'] ?? '',
            'city' => $input['city'] ?? '',
            'area' => $input['area'] ?? '',
            'address' => $input['address'] ?? '',
            'file' => $input['file'] ?? '',
            'file_name' => $input['file_name'] ?? '',
            'lat' => $input['lat'] ?? 0,
            'lng' => $input['lng'] ?? 0,
        ];

        // 发单的商户
        $data['merchant_id'] = $merchant['id'];

        $task = TaskModel::where(['is_deleted'=>0, 'status'=>1])->where('merchant_id', $merchant['id'])->where('id', $data['id'])->find();
        if (empty($task)) $this->error('订单任务不存在');
        if ($task->task_status != TaskModel::TASK_STATUS__PENDING_REVIEW) $this->error('当前状态不允许编辑');

        if (empty($data['category_id'])) $this->error('订单任务类型不能为空');
        $category = CategoryModel::where(['is_deleted'=>0, 'status'=>1])->where('id', $data['category_id'])->find();
        if (empty($category)) $this->error('订单任务类型不存在');

        if (empty($data['exec_at'])) $this->error('订单任务时间不能为空');
        if(strtotime($data['exec_at']) === false) $this->error('订单任务时间格式不正确');

        if (empty($data['name'])) $this->error('订单任务名称不能为空');

        if (empty($data['province']) || empty($data['city']) || empty($data['area'])) $this->error('订单任务地区不正确');

        if (empty($data['address'])) $this->error('订单任务详细地址不能为空');

        if (empty($data['desc'])) $this->error('订单任务描述不能为空');

        if (empty($data['require'])) $this->error('订单任务要求不能为空');

        if (empty($data['money'])) $this->error('订单任务报酬不能为空');

        if (empty($data['file'])) $this->error('审批文件不能为空');

        $data['place'] = $data['province'].$data['city'].$data['area'].$data['address'];

        $data['latlng'] = $data['lat'].','.$data['lng'];

        TaskModel::update($data);

        $this->success('ok');
    }

    /**
     * 订单任务列表（商家发布页面）
     */
    public function taskList()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $query = TaskModel::where(['is_deleted'=>0, 'status'=>1])->with(['category'])
            ->field('id,name,exec_at,place,money,category_id,money,task_status')
            ->where('merchant_id', $merchant['id'])
            ->order('id desc');
        // 筛选项
        $task_status = $this->request->post('task_status', '');
        if (!empty($task_status)) $query->where('task_status', $task_status);
        $list = get_list($query);
        // 数据清洗
        foreach ($list['list'] as &$vo){
            $vo['exec_at'] = date('Y-m-d H:i', strtotime($vo['exec_at']));
            $vo['category'] = array_keep($vo['category'], ['id', 'name', 'img']);
        }
        $this->success('ok', $list);
    }

    /**
     * 订单任务列表2（商家管理订单任务页面）
     */
    public function taskList2()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $query = TaskModel::alias('t')->where(['t.is_deleted'=>0, 't.status'=>1])->with(['category', 'task_order'])
            ->field('t.*')
            ->join('task_order to', 'to.id = t.order_id', 'left')
            ->where('t.merchant_id', $merchant['id'])
            ->order('t.id desc');
        // 筛选项
        $type = $this->request->post('type', 0);
        if (empty($type)){
            $query->whereIn('t.task_status', [
                TaskModel::TASK_STATUS__PENDING_ACCEPTANCE,
                TaskModel::TASK_STATUS__PENDING_COMPLETION,
                TaskModel::TASK_STATUS__COMPLETED,
            ]);
        }else if ($type == 1){
            $query->where('t.task_status', TaskModel::TASK_STATUS__PENDING_ACCEPTANCE)
                ->whereTime('t.exec_at', '>', date('Y-m-d H:i:s'));
        }else if ($type == 2){
            $query->where('t.task_status', TaskModel::TASK_STATUS__PENDING_COMPLETION);
        }else if ($type == 3){
            $query->where('t.task_status', TaskModel::TASK_STATUS__PENDING_COMPLETION)
                ->where('to.status', OrderModel::STATUS__PENDING_REVIEW);
        }else if ($type == 4){
            $query->whereIn('t.task_status', [
                TaskModel::TASK_STATUS__PENDING_ACCEPTANCE,
                TaskModel::TASK_STATUS__PENDING_COMPLETION,
            ])
                ->whereTime('t.exec_at', '<', date('Y-m-d H:i:s'));
        }else{
            $this->error('type值错误');
        }
        $list = get_list($query);
        // 数据清洗
        foreach ($list['list'] as &$vo){
            $vo['is_expired'] = strtotime($vo['exec_at']) < time() ? 1 : 0;
            $vo['exec_at'] = date('Y-m-d H:i', strtotime($vo['exec_at']));
            $vo['category'] = array_keep($vo['category'], ['id', 'name', 'img']);
        }
        $this->success('ok', $list);
    }

    /**
     * 订单任务详情（商家发布页面）
     */
    public function taskDetail()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $id = $this->request->post('id', 0);
        if (empty($id)) $this->error('ID不能为空');
        $task = TaskModel::where(['is_deleted'=>0, 'status'=>1])->with(['category', 'task_order'])
            ->field('id,name,exec_at,place,money,category_id,money,desc,require,task_status,review_reason,order_id,province,city,area,address,file,lat,lng,file_name')
            ->where('merchant_id', $merchant['id'])
            ->where('id', $id)
            ->find();
        if (empty($task)) $this->error('订单任务不存在');
        $task = $task->toArray();
        $task['exec_at'] = date('Y-m-d H:i', strtotime($task['exec_at']));
        $task['category'] = array_keep($task['category'], ['id', 'name', 'img']);
        $this->success('ok', $task);
    }

    /**
     * 审核订单任务订单
     */
    public function reviewOrder()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');
        if (empty($merchant['phone'])) $this->error('请先登录');

        $id = $this->request->post('id', 0);
        $review_status = $this->request->post('review_status', 0);
        $review_reason = $this->request->post('review_reason', '');
        // 当前只允许通过审核
        if ($review_status != 1) $this->error('审核状态不正确');
        if (empty($id)) $this->error('ID不能为空');
        Db::startTrans();
        try {
            $task = TaskModel::where(['is_deleted'=>0, 'status'=>1])
                ->where('merchant_id', $merchant['id'])
                ->where('task_status', TaskModel::TASK_STATUS__PENDING_COMPLETION)
                ->where('id', $id)
                ->lock(true)
                ->find();
            if (empty($task)) $this->error('订单任务不存在');
            $task_order = OrderModel::where(['is_deleted'=>0])
                ->where('status', OrderModel::STATUS__PENDING_REVIEW)
                ->where('id', $task->order_id)
                ->lock(true)
                ->find();
            if (empty($task_order)) $this->error('订单任务订单不存在');
            // 变更任务状态
            $task->task_status = TaskModel::TASK_STATUS__COMPLETED;
            $task->save();
            $task_order->status = OrderModel::STATUS__COMPLETED;
            $task_order->review_at = date('Y-m-d H:i:s');
            $task_order->update_at = date('Y-m-d H:i:s');
            $task_order->save();
            // 商户-增加支出金额和支出记录
            $merchant = MerchantModel::where('id', $task->merchant_id)
                ->lock(true)
                ->find();
            ExpenseRecordModel::create([
                'merchant_id' => $merchant->id,
                'type' => 1,
                'amount' => $task->money,
                'before' => $merchant->expense,
                'after' => $merchant->expense + $task->money,
                'remark' => '',
                'task_order_id' => $task_order->id,
            ]);
            $merchant->expense += $task->money;
            $merchant->save();
            // 飞手-增加余额和余额记录
            $pilot = PilotModel::where('id', $task_order->pilot_id)
                ->lock(true)
                ->find();
            BalanceRecordModel::create([
                'pilot_id' => $pilot->id,
                'type' => 1,
                'amount' => $task_order->money,
                'before' => $pilot->balance,
                'after' => $pilot->balance + $task_order->money,
                'remark' => '',
                'task_order_id' => $task_order->id,
            ]);
            $pilot->balance += $task_order->money;
            $pilot->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('ok', $task);
    }

    /**
     * 订单任务支出列表
     */
    public function expenseList()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $query = ExpenseRecordModel::with(['task_order'=>['task'=>['category']]])
            ->where('merchant_id', $merchant['id'])
            ->order('id desc');
        $list = get_list($query);
        // 数据清洗
        foreach ($list['list'] as &$vo){
            if ($vo['type'] == 1){
                $vo['task'] = [
                    'name' => $vo['task_order']['task']['name'] ?? '',
                    'category_name' => $vo['task_order']['task']['category']['name'] ?? ''
                ];
            }
            unset($vo['task_order']);
        }
        $this->success('ok', $list);
    }

    /**
     * 商户认证
     */
    public function verificationLatest()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $apply = VerificationModel::with(['merchant'])
            ->where('merchant_id', $merchant['id'])
            ->order('id desc')
            ->find();
        $this->success('ok', $apply);
    }

    /**
     * 提交认证申请
     */
    public function verification()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');
        if (empty($merchant['phone'])) $this->error('请先登录');

        if (!empty($merchant['is_verification'])) $this->error('您已完成认证');

        $apply = VerificationModel::where('merchant_id', $merchant['id'])->where('status', 0)->find();
        if (!empty($apply)) $this->error('您有待审核的认证申请，请耐心等待');

        $input = $this->request->post();
        $data = [
            'company' => $input['company'] ?? '',
            'id_company' => $input['id_company'] ?? '',
            'phone' => $input['phone'] ?? '',
            'legal_person' => $input['legal_person'] ?? '',
            'legal_person_phone' => $input['legal_person_phone'] ?? '',
            'license_img' => $input['license_img'] ?? '',
            'license_img2' => $input['license_img2'] ?? '',
            'merchant_id' => $merchant['id'],
        ];

        if (empty($data['company'])) $this->error('公司名称不能为空');

        if (empty($data['id_company'])) $this->error('纳税人识别号不能为空');

        if (empty($data['phone'])) $this->error('联系电话不能为空');

        if (empty($data['legal_person'])) $this->error('法人姓名不能为空');

//        if (empty($data['legal_person_phone'])) $this->error('法人联系电话不能为空');

        if (empty($data['license_img'])) $this->error('营业执照不能为空');

        $res = VerificationModel::create($data);

        if (!empty($res)){
            $this->success('ok');
        }else{
            $this->error('提交申请失败，请稍后重试');
        }
    }
}